(function (window, $) {
    var OutlineApp = {};
    var returnData = new Array();
    var rootNodeData = new Array();
    var defalutConfig = {
        multi: false,//单选多选
        rootPath: basePath + "/outline/getRootOutlines.json",
        currentPath: basePath + "/outline/getOutLineListExt.json",
        questionListPath: basePath + "/outline/getQuestionList.json",
        questionDetailPath: basePath + "/question/getQuestionById.json",
        relatedQuestionPath: basePath + "/question/getRelatedQuestionById.json",
        selectType: "checkbox",
        currentTreeId: ""
    };
    var config = {};
    OutlineApp.Tree = {
        selectOutLine: function (exdconfig) {
            config = {};
            $.extend(true, config, defalutConfig, exdconfig);
            initRootNodes(config.currentTreeId, config.currentTreeId + "Selected", config.multi);
        },
        removeLi: function (id, treeId) {
            if (null != returnData && returnData.length > 0) {
                var i = 0;
                for (i = 0; i < returnData.length; i++) {
                    if (returnData[i].uid == id) {
                        $("#" + treeId + id).remove();
                        var treeObj = $.fn.zTree.getZTreeObj(treeId);
                        var node = treeObj.getNodeByParam("id", id, null);
                        treeObj.checkNode(node, false, false);
                        returnData.splice(i, 1);
                        return true;
                    }
                }
            }
        },

        /**
         * 根据题目id，题目类型添加题目
         * @param id
         * @param type
         */
        addQues: function (id, type) {
            var quesIds = new Array();
            var index = $("#quesTitle").attr("data-index");
            index = index == "" ? 0 : index;
            var isRepeat = false;
            $(".quesId").each(function () {
                if (id == $(this).val()) {
                    BootstrapDialog.alert({title: "提示", message: "该题目已添加，请勿重复添加"});
                    isRepeat = true;
                    return false;
                }

            })
            if (isRepeat) {
                return false;
            }
            if (type == 2) {
                //需要添加关联的题目
                $.ajax({
                    url: config.relatedQuestionPath,
                    type: "get",
                    data: {"id": id},
                    dataType: "json",
                    success: function (r) {
                        if (r.length == 0) {
                            getQuesDetail(quesIds, id, index);
                        } else {
                            for (var key = 0; key < r.length; key++) {
                                var data = r[key];

                                if ($.inArray(data.id, quesIds) == -1) {
                                    var str = getHtml(data, index);

                                    $quesTitle = $("#quesTitle");
                                    $quesTitle.parent().append(str);
                                    index++;
                                    $("#quesTitle").attr("data-index", index);
                                    quesIds.push(data.id);
                                }
                            }
                        }
                    }
                });
            } else {
                getQuesDetail(quesIds, id, index);
            }

        },
        readQues: function (quesId) {
            var param = {"id": quesId};
            var url = basePath + "/question/readJump?" + $.param(param);
            layer.open({
                closeBtn: 2,
                type: 2,
                title: '查看题目详情',
                shadeClose: true,
                shade: 0.8,
                area: ['735px', '700px'],
                content: url,
                success: function (layero, index) {
                    console.log(layero, index);
                    var $btn = $("#layui-layer-iframe" + index + "").contents().find("button");
                    $btn.hide();
                    $btn.parent().hide();
                    $btn.parent().parent().hide();
                }
            })
        }
    };
    var getQuesDetail = function (quesIds, id, index) {
        $.ajax({
            url: config.questionDetailPath,
            type: "get",
            data: {"id": id},
            dataType: "json",
            success: function (r) {
                var data = r;
                var str = getHtml(data, index);
                $quesTitle = $("#quesTitle");
                $quesTitle.parent().append(str);
                index++;
                $("#quesTitle").attr("data-index", index);

                quesIds.push(data.id);
            }
        })
    }

    var initRootNodes = function (_treeId, _selectTreeId, multi) {
        $.ajax({
            url: config.rootPath,
            type: "get",
            dataType: "json",
            success: function (r) {
                var treeRNodes = new Array();
                ;
                for (var key = 0; key < r.length; key++) {
                    var node = r[key];
                    var rNode = {};
                    rNode.content = node.rootName;
                    rNode.yearNum = node.rootYear;
                    rNode.outlineType = node.rootType;
                    rNode.isParent = true;
                    treeRNodes.push(rNode);
                }

                initTree(_treeId, _selectTreeId, treeRNodes);
            }
        })
            .fail(function () {
                BootstrapDialog.alert({title: "提示", message: "获取大纲数据异常，请联系管理员"});
            })

    };

    var defaultSetting = {
        view: {
            showLine: true,
            dblClickExpand: false,
            showIcon: true
        },
        data: {
            simpleData: {
                enable: true,
                idKey: "id",
                pIdKey: "parentId",
                rootPId: null
            },
            key: {
                name: "content"
            }
        }
    };

    var initTree = function (_treeId, _selectTreeId, _treeZNodes) {
        var multi = config.multi;
        var settings = {};
        var userSetting = {
            check: {
                enable: true,
                autoCheckTrigger: true,
                chkboxType: {"Y": "ps", "N": "ps"},
                chkStyle: config.selectType
            },
            async: {
                enable: true,
                url: config.currentPath,
                autoParam: ["id=parentId", "yearNum", "outlineType"],
                type: "get",
                dataFilter: function (treeId, parentNode, responseData) {
                    return responseData;
                },
            },
            callback: {
                onClick: function (event, treeId, treeNode) {
                    var zTree = $.fn.zTree.getZTreeObj(_treeId);
                    if (treeNode.isParent) {
                        zTree.expandNode(treeNode, "refresh");
                        return;
                    }
                    //如果是限选一人的情况
                    if (!multi) {
                        for (var i = 0; i < returnData.length; i++) {
                            var tId = returnData[i].tId.substring(0, returnData[i].tId.indexOf("_"));
                            if (_treeId == tId) {
                                returnData.splice(i, 1);
                            }
                        }
                    }
                    //判断这个人有没有选择过
                    if (!treeNode.checked) {
                        addLi(treeNode, treeId, _selectTreeId);
                    } else {//如果是取消，则进行删除
                        OutlineApp.Tree.removeLi(treeNode.id, treeId);
                        if (!multi) {
                            var treeObj = $.fn.zTree.getZTreeObj(treeId);
                            var node = treeObj.getNodeByParam("id", treeNode.id, null);
                            treeObj.checkNode(node, false, false);
                        }
                        $("[id='" + treeNode.id + "']").remove();
                    }
                },
                onCheck: zTreeOnCheck,
                beforeCheck: zTreeBeforeCheck,

            }
        };

        $.extend(true, settings, defaultSetting, userSetting);
        $.fn.zTree.destroy(_treeId);
        $.fn.zTree.init($("#" + _treeId), settings, _treeZNodes);
    };

    function zTreeOnCheck(event, treeId, treeNode) {
        var multi = config.multi;
        var selectTreeId = treeId + "Selected";

        if (!treeNode.isParent) {
            if (!multi) {
                for (var i = 0; i < returnData.length; i++) {
                    var tId = returnData[i].tId.substring(0, returnData[i].tId.indexOf("_"));
                    if (treeId == tId) {
                        returnData.splice(i, 1);
                    }
                }
            }
            //如果是选中，进行添加
            if (treeNode.checked) {
                addLi(treeNode, treeId, selectTreeId);
            } else {//如果是取消，则进行删除
                OutlineApp.Tree.removeLi(treeNode.id, treeId);
                $("[id='" + treeNode.id + "']").remove();
            }
        }
    }

    function zTreeBeforeCheck(treeId, treeNode) {
        var zTree = $.fn.zTree.getZTreeObj(treeId);
        if (treeNode.isParent) {
            zTree.expandNode(treeNode, true);
        }

    }

    function addLi(treeNode, treeId, selectTreeId) {
        var selectType = config.selectType;

        var outlineId = treeNode.id;
        $.ajax({
            url: config.questionListPath,
            type: "get",
            data: {"outlineId": outlineId},
            dataType: "json",
            success: function (r) {
                for (var key = 0; key < r.length; key++) {
                    var str = '';
                    if (r[key].realQuestionYear != '' && r[key].realQuestionYear != null) {
                        str =
                            "<li title='" + r[key].question + "' id = '" + outlineId + "'>" +
                            "<a href='javascript:void(0);' onclick = 'javascript:OutlineApp.Tree.addQues(\"" + r[key].id + "\",\"" + r[key].quesType + "\");'>" + r[key].quesCode + "</a>" +
                            "&nbsp;&nbsp;&nbsp;&nbsp;" +
                            "<a href='javascript:void(0);' onclick = 'javascript:OutlineApp.Tree.readQues(\"" + r[key].id + "\");'>查看详情</a>" +
                            "&nbsp;&nbsp;&nbsp;&nbsp;真题题号：" + r[key].realQuestionYear + r[key].realQuestionNo +
                            "</li>";
                    } else {
                        str = "<li title='" + r[key].question + "' id = '" + outlineId + "'>" +
                            "<a href='javascript:void(0);' onclick = 'javascript:OutlineApp.Tree.addQues(\"" + r[key].id + "\",\"" + r[key].quesType + "\");'>" + r[key].quesCode + "</a>" +
                            "&nbsp;&nbsp;&nbsp;&nbsp;" +
                            "<a href='javascript:void(0);' onclick = 'javascript:OutlineApp.Tree.readQues(\"" + r[key].id + "\");'>查看详情</a>"
                    }
                    $("#" + selectTreeId).append(str);
                }
                returnData.push(treeNode);
                var zTree = $.fn.zTree.getZTreeObj(treeId);
                var nodes = zTree.getCheckedNodes(true);
                if (selectType == "radio") {
                    for (var i = 0, l = nodes.length; i < l; i++) {
                        zTree.checkNode(nodes[i], false, true);
                    }
                }
                ;
                zTree.checkNode(treeNode, true, true);
            }
        })
            .fail(function () {
                BootstrapDialog.alert({title: "提示", message: "获取题目数据异常，请联系管理员"});
            })

    };

    window.OutlineApp = OutlineApp;

})(window, jQuery);